package spring.mvc.web.test.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import spring.mvc.web.test.constants.Constants;

import spring.mvc.web.test.pojo.po.UserPo;
import spring.mvc.web.test.pojo.vo.RespCodeTypeEnum;
import spring.mvc.web.test.pojo.vo.RespResult;
import spring.mvc.web.test.service.UserService;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@EnableSwagger2
@RestController
@RequestMapping
@RestControllerAdvice
@Api(tags = "用户业务接口")
public class UserController {
    @Resource
    UserService userService;

    @ApiOperation("用户注册")
    @PostMapping(value = "/register")
    public RespResult register(@RequestBody UserPo userPo){
        RespResult register = userService.register(userPo);
        System.out.println(register);
        register.setMessage("注册成功");
        return  register;
    }
    @ApiOperation("用户登录")
    @RequestMapping(value = "/login")
    public RespResult login(@RequestBody UserPo userPo, HttpServletRequest request) {
        RespResult result = new RespResult();
        try {
            RespResult<UserPo> login = userService.login(userPo);
            result.setCode(RespCodeTypeEnum.SUCCESS.getValue());
            result.setData(login);
            //登录成功，保存用户信息到session
            request.getSession().setAttribute(Constants.SESSION_KEY_LOGIN_USER, userPo);
        } catch (RuntimeException e) {
            result.setCode(RespCodeTypeEnum.FAILED.getValue());
            result.setMessage(e.getMessage());
        }
        return result;
    }
  @ApiOperation(value = "文件的操作")
    @RequestMapping(value = {"upload"}, method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    @ResponseBody

    public String upload(@RequestParam("name") String name,@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "{msg:'上传失败'}";
        }

        //读取文件到本地
        String fileName = file.getOriginalFilename();
        int fileSuffixTag = fileName.lastIndexOf(".");
        String filePath = "E:\\temp\\"+name
                + file.getOriginalFilename().substring(fileSuffixTag, fileName.length());
        file.transferTo(new File(filePath));
        return "{msg:'上传成功'}";
    }
}


